package com.example.petstoreservice.controller;

import com.example.petstoreservice.entity.Product;
import com.example.petstoreservice.entity.Result;
import com.example.petstoreservice.entity.Supplier;
import com.example.petstoreservice.service.SupplierService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@CrossOrigin
@RequestMapping("/supplier")
public class SupplierController {
    @Autowired
    private SupplierService supplierService;
    @GetMapping("/shops")
    public Result<List<Supplier>> getNearbyShops(@RequestParam String location) {
        Result<List<Supplier>> res=new Result<>();
        // 假设 location 格式为 "lng,lat"
        String[] loc = location.split(",");
        double lng = Double.parseDouble(loc[0]);
        double lat = Double.parseDouble(loc[1]);
        res.setStatusCode("200");
        res.setData(supplierService.findNearbyShops(lng,lat));
        return res;
    }
    @GetMapping("/all")
    public Result<List<Supplier>> getAll(){
        Result<List<Supplier>> res=new Result<>();
        res.setData(supplierService.getAll());
        return res;
    }
    @PostMapping("/update")
    public Result<?> update(@RequestBody Supplier supplier){
        Long supplierId=supplier.getSupplierId();
        Supplier currentSupplier=supplierService.getById(supplierId);
        if(supplier.getSupplierName()!=null){
            currentSupplier.setSupplierName(supplier.getSupplierName());
        }
        if(supplier.getDescription()!=null){
            currentSupplier.setDescription(supplier.getDescription());
        }
        if(supplier.getAddress()!=null){
            currentSupplier.setAddress(supplier.getAddress());
        }
        if(supplier.getLng()!=null){
            currentSupplier.setLng(supplier.getLng());
        }
        if(supplier.getLat()!=null){
            currentSupplier.setLat(supplier.getLat());
        }
        if(supplierService.update(currentSupplier)){
            return Result.success("修改成功!");
        }else{
            return Result.fail("修改失败!");
        }
    }
    @GetMapping("/search/{keyword}")
    public Result<List<Supplier>> search(@PathVariable String keyword){
        Result<List<Supplier>> res=new Result<>();
        res.setData(supplierService.search(keyword));
        res.setMessage("查找成功");
        return res;
    }

}
